# utils/logger.py
import logging
import os
from datetime import datetime


class Logger:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Logger, cls).__new__(cls)
        return cls._instance

    def __init__(self, log_level=logging.INFO):
        if not hasattr(self, 'initialized'):
            self.logger = logging.getLogger('test_framework')
            self.logger.setLevel(log_level)

            # 避免重复添加handler
            if not self.logger.handlers:
                # 创建控制台handler
                console_handler = logging.StreamHandler()
                console_handler.setLevel(log_level)

                # 创建文件handler
                log_dir = "logs"
                if not os.path.exists(log_dir):
                    os.makedirs(log_dir)

                log_file = os.path.join(log_dir, f"test_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log")
                file_handler = logging.FileHandler(log_file, encoding='utf-8')
                file_handler.setLevel(log_level)

                # 创建formatter
                formatter = logging.Formatter(
                    '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
                )

                console_handler.setFormatter(formatter)
                file_handler.setFormatter(formatter)

                # 添加handler到logger
                self.logger.addHandler(console_handler)
                self.logger.addHandler(file_handler)

            self.initialized = True

    def get_logger(self):
        return self.logger


# 全局日志实例
test_logger = Logger().get_logger()